import router from "./router";
import projectSetting from "@/settings/projectSetting";
import { store } from "@/store/index";
import { message } from "ant-design-vue";
// get token from cookie
import { getToken } from "@/utils/auth";
// 路由模块
import asyncRoutes from "@/router/routes/index";
// 404路由模块
import { pathMatch } from "@/router/routes/staticRoutes";
// 白名单
const whiteList = ["/login", "/register", "/401", "/404", "403"];

const indexRoute = {
  path: "/",
  component: () => import("@/layout/index.vue"),
  redirect: "/home",
  meta: {
    title: "Index",
  },
  children: [],
};

// 添加路由
function addAsyncRoutes(list) {
  indexRoute.children = list;
  router.addRoute(indexRoute);
  // 添加404界面;
  router.addRoute(pathMatch);
  saveData();
}

// 前端控制路由
if (projectSetting.routesMode === "roles") {
  addAsyncRoutes(asyncRoutes);
  // 保存路由到store
  store.commit("routes/setRoutesList", asyncRoutes);
}

// 保存数据
function saveData() {
  // 获取缓存路由的name集合
  const names = router.getRoutes().reduce((cur, next) => {
    if (next.meta && next.meta.keepAlive) {
      cur.push(next.name);
    }
    return cur;
  }, []);
  // 保存缓存路由
  store.commit("routes/setCacheKeepAlive", names);
  // 保存路由到标签页模块
  store.commit("tagsViewRoutes/setTagsViewRoutes", router.getRoutes());
}
//定义变量判断是否已经动态添加过，如果刷新后load永远为 0
let load = 0;

function setWebTitle(title) {
  const webTitle = title || "";
  const { globalTitle } = store.state.themeConfig;
  document.title = `${webTitle} - ${globalTitle}` || globalTitle;
}

router.beforeEach((to, from, next) => {
  // 获取浏览器缓存token
  const hasToken = getToken();
  if (hasToken) {
    /* has token*/
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      const hasGetUserInfo = store.state.user.userInfo.userName;
      if (hasGetUserInfo) {
        // 防止刷新页面，动态路由丢失
        if (load === 0 && projectSetting.routesMode !== "roles") {
          load++;
          //再次调用存储菜单数据
          store.dispatch("routes/getRoutesList").then(async (accessRoutes) => {
            // 动态添加可访问路由表
            addAsyncRoutes(accessRoutes);
            //添加后跳转到应访问的地址
            next({ path: to.path });
          });
        } else {
          next();
        }
      } else {
        try {
          // get user info
          store.dispatch("user/getUserInfo").then(() => {
            // 前端控制路由
            if (projectSetting.routesMode === "roles") {
              next({
                ...to,
                replace: true,
              });
            } else {
              // 后端返回路由
              store
                .dispatch("routes/getRoutesList")
                .then(async (accessRoutes) => {
                  // 动态添加可访问路由表
                  addAsyncRoutes(accessRoutes);
                  next({
                    ...to,
                    replace: true,
                  });
                });
            }
          });
        } catch (error) {
          // remove token and go to login page to re-login
          store.dispatch("user/resetToken").then(() => {
            message.error(error || "Has Error");
            next(`/login?redirect=${to.path}`);
          });
        }
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
    }
  }
  setWebTitle(to.meta.title);
});
